<template>
  <div class="container">
    <div class="sign-in">
      <!-- 登录 -->
      <div class="loginLogo"
           @click="routerHome">
        <div class="colorS">小囧科技</div>
      </div>
      <div class="loginFrom">
        <el-form class="form login-form clear-fix"
                 ref="loginFormRef"
                 :model="loginForm"
                 :rules="rules">
          <el-form-item label="手机号码"
                        prop="mobile">
            <el-input v-model="loginForm.mobile"
                      placeholder="请输入手机号码"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码"
                        prop="pass">
            <el-input v-model="loginForm.pass"
                      type="password"
                      placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="12">
                <el-button @keyup.enter.native="submitForm()"
                           type="danger"
                           class="form-btn submit-btn"
                           @click="submitForm()"
                           :loading="loadingButton">{{loadingButtonText}}</el-button>
              </el-col>
              <el-col :span="12">
                <el-button class="form-btn reset-btn"
                           @click="resetForm()">重置</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <!-- 找回密码 -->
          <div class="tiparea">
            <span>忘记密码</span>
            <i>|</i>
            <span @click="toregister">注册</span>
          </div>
        </el-form>
      </div>
    </div>
    <div class="sign-up"></div>
  </div>
</template>

<script>
import { ref, reactive, unref, toRefs, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// 登录api
import { Login } from '@/network/login'
// 状态管理
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { setLocal } from '@/utils/cookie'
// 对密码和邮箱进行类型限制
export default {
  setup () {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const validePhone = (rule, value, callback) => {
      const isPhone =
        /^(0|86|17951)?(13[0-9]|15[0-9]|166|17[3678]|18[0-9]|19[0-9]|14[57])[0-9]{8}$/.test(
          value
        )
      if (!isPhone) {
        callback(new Error('手机号码格式错误'))
      }
      callback()
    }
    const validatePass = (rule, value, callback) => {
      //  密码只能由大小写英文字母或数字开头，且由大小写英文字母_.组成
      const reg = /^[A-Za-z0-9][A-Za-z0-9_.]{5,14}$/
      if (!reg.test(value)) {
        callback(
          new Error('密码由字母或数字开头，且只能为字母,数字,下划线及（.）')
        )
      } else {
        callback()
      }
    }
    const loginFormRef = ref(null)

    const state = reactive({
      loadingButtonText: '提交',
      loadingButton: false,
      loginForm: {
        mobile: +decodeURIComponent(route.query.mobile)
          ? decodeURIComponent(route.query.mobile)
          : '',
        pass: '',
      },
      rules: {
        mobile: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { validator: validePhone, trigger: 'blur' },
        ],
        pass: [
          { required: true, message: '不能为空', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码位数只能在6~15之间',
            trigger: 'blur',
          },
          { validator: validatePass, trigger: 'blur' },
        ],
      },
    })
    // 重置表单
    const resetForm = () => {
      const form = unref(loginFormRef)
      form.resetFields()
    }
    // 表单提交
    const submitForm = () => {
      loginFormRef.value.validate(async (valid) => {
        if (valid) {
          state.loadingButton = true
          state.loadingButtonText = '提交中...'
          const params = {
            userCode: state.loginForm.mobile,
            password: state.loginForm.pass,
          }
          await Login(params).then((res) => {
            if (res.code == 200) {
              ElMessage({
                message: '登录成功',
                type: 'success',
                duration: 1000,
              })
              state.loadingButton = false
              state.loadingButtonText = '确定'
              // 获取值

              // 
              const token = res.result.rayAccessToken
              store.commit('app/SET_GETTOKEN', token)
              localStorage.setItem(
                'raysaleMobileuserInfo',
                JSON.stringify(userInfo)
              )
              setLocal('raySaleToken', token)
              router.push({
                path: route.query.redirect ? route.query.redirect : '/home',
                query: {
                  id: route.query.itemid
                }
              })
            } else {
              ElMessage(`${res.message}`)
              state.loadingButton = false
              state.loadingButtonText = '提交'
            }
          })
        } else {
          console.log('验证错误')
          return false
        }
      })
    }
    const toregister = () => {
      router.push('/register')
    }
    const routerHome = () => {
      router.push('./')
    }
    onMounted(() => {
      document.onkeydown = (e) => {
        if (e.keyCode == 13 || e.key == 'enter') {
          submitForm()
        }
      }
    })
    return {
      ...toRefs(state),
      loginFormRef,
      resetForm,
      submitForm,
      routerHome,
      toregister,
    }
  },
}
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
.sign-in {
  background: url("../../assets/images/loginbg.png") no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
  position: relative;
  font-family: var(--font-family);
  cursor: pointer;
  .loginLogo {
    display: flex;
    justify-content: center;
    padding-top: 100px;
    .colorS {
      font-size: 26px;
      color: #fff;
    }
  }
}
.loginFrom {
  width: 800px;
  padding: 50px 50px;
  border-radius: 12px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  /deep/.el-form-item__content {
    padding-top: 12px;
  }
  /deep/.el-form-item__label {
    padding-top: 12px;
  }
  /deep/.el-form {
    border-radius: 8px;
  }
}
.tiparea {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  > span {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #606266;
    &:hover {
      color: red;
      cursor: pointer;
    }
  }

  > i {
    font-style: normal;
    display: inline-block;
    padding: 0 5px;
    color: #999;
  }
}

.login-form {
  box-shadow: 5px 5px 5px 5px darken(#ccc, 0.1);
  padding: 30px;
}
.form-btn {
  width: 48%;
}
.reset-btn {
  float: right;
}

.el-form {
}
</style>